import json
import sys
import os
import logging
import datetime
import time
import threading
import Recommender.JMQ as JMQ
import Recommender.FeatureRepresentation as Feature
import Recommender.RecommenderTagBased as RecommenderTagBased


from Recommender.Config import *
config = Config()
database = config.DataBase()

# content_by_cms：cms后台编辑手工发布得
# content_by_virtualnumber：生成虚拟号后自动分发得，
# content_by_sync：数据部、抓取、等定时大量数据同步
def WaitArticleFlow(topic):

    if topic == "x":
        topic = "content_by_cms,content_by_virtualnumber,content_by_sync"

    # ---Connect MQ---
    jmq_client = JMQ.JMQClient(
            user=configFile["JMQUsername"],
            app="RecArticle",
            proxy_url=configFile["JMQAddressPort"],
            password=configFile["JMQPassword"],
            topic=topic)

    print("Subscribe Topic ", topic)

    for msg in jmq_client.consumer():
        print(datetime.datetime.now())
        print(topic, ' 消费消息：{}'.format(msg))
        try:
            jsonObj = json.loads(msg)
            articleId = jsonObj["articleId"]
            title = ""
            if "title" in jsonObj:
                title = jsonObj["title"]
            content = ""
            if "content" in jsonObj:
                content = jsonObj["content"]

            #
            Feature.AddTag_on_Article(database, articleId, content, "TopTFIDF")

        except Exception as e:
            print(repr(e))
        pass


threading.Thread(target=WaitArticleFlow, args=("x",)).start()
threading.Thread(target=WaitArticleFlow, args=("content_by_cms",)).start()
# threading.Thread(target=WaitArticleFlow, args=("content_by_virtualnumber",)).start()
# threading.Thread(target=WaitArticleFlow, args=("content_by_sync",)).start()
#

while True:
    time.sleep(10)
